package logic

import (
	"al/cache"
	"al/models/mysql"
	"context"
	"errors"

	"al/alrpc/alrpc"
	"al/alrpc/internal/svc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *alrpc.LoginRequest) (*alrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendCode"+in.Mobile).Result()
	if result != in.SendCode {
		return nil, errors.New("短信验证码错误,请重新输入")
	}

	var findUser mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&findUser)
	if in.Mobile != findUser.Mobile {
		return nil, errors.New("用户不存在,请先进行注册")
	}
	if in.Password != findUser.Password {
		return nil, errors.New("密码错误,请重新输入")
	}

	var user mysql.User
	mysql.DB.Debug().Find(&user)

	return &alrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
